package com.stsdai.portal.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.stsdai.manager.pojo.Receiver;
import com.stsdai.manager.pojo.User;
import com.stsdai.manager.service.ReceiverService;
import com.stsdai.sso.service.UserService;

@Controller
@RequestMapping("receiver")
public class ReceiverController {
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private ReceiverService receiverService;
	
	@RequestMapping(value = "save", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> saveReceiver(Receiver receiver,@CookieValue("STSD_TICKET") String ticket){
		// 通过ticket获取用户
		User user = userService.queryUserByTicket(ticket);
		Date date = new Date();
		
		receiver.setUserid(user.getId());
		receiver.setCreated(date);
		receiver.setUpdated(date);
		
		Map<String, Object> map = new HashMap<>();
		try {
			receiverService.save(receiver);
			map.put("status", 200);
		} catch (Exception e) {
			
		}
		return map;
	}
	
	@RequestMapping("query")
	public String queryReceiver(Model model, @CookieValue("STSD_TICKET") String ticket){
		// 通过ticket获取用户
		User user = userService.queryUserByTicket(ticket);
		
		List<Receiver> receiverList = receiverService.queryReceiver(user.getId());
		model.addAttribute("receiverList", receiverList);
		
		return "add-address";
	}
	
	
	@RequestMapping(value = "delete", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> deleteReceiver(String id) {
		Long oid = Long.parseLong(id);
		Map<String, Object> map = new HashMap<>();
		try {
		this.receiverService.deleteById(oid);
		map.put("status", 200);
		} catch (Exception e) {
			
		}
		return map;

	}

}
